package com.bulletelc.apollopre.module.main.center.address.list;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.AddressDetailBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/23
 * desc  : TODO
 */

public class AddressPresenter extends BasePresenter<AddressContract.View> implements AddressContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getAddressList() {
        getAddressListImp();
    }

    @Override
    public void deleteAddress(int addressId, int position) {
        deleteAddressImp(addressId, position);
    }

    @Override
    public void setDefaultAddress(int addressId) {
        setDefaultAddressImp(addressId);
    }

    /**
     * 获取地址列表数据
     */
    private void getAddressListImp() {
        OkGo.<String>get(NetWorkPath.GET_USER_ADDRESS)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseAddressList(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorAddressList(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * @param response
     */
    public void parseAddressList(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject objMeta = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getName().contains("_links");
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create();
                    Type type = new TypeToken<List<AddressDetailBean>>() {}.getType();
                    List<AddressDetailBean> addressDetailBeans = gson.fromJson(object.getJSONArray("data").toString(), type);
                    if (isViewAttached()) {
                        getView().onSuccessAddressList(addressDetailBeans);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddressList(objMeta.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddressList("数据解析错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailAddressList(response.body().toString());
            }
        }

    }

    /**
     * 删除地址
     *
     * @param addressId
     */
    private void deleteAddressImp(int addressId, final int position) {
        OkGo.<String>post(NetWorkPath.POST_USER_ADDRESS_DELETE + "?id=" + addressId)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(MyApplication.getToken()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseDeleteAddress(response, position);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorDelete(response.getException().toString());
                        }
                    }
                });

    }

    /**
     * 解析删除的结果数据
     *
     * @param response
     */
    private void parseDeleteAddress(Response<String> response, int position) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessDelete(position);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailDelete(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorDelete("数据解析有误");
                }
            }

        } else {
            if (isViewAttached()) {
                getView().onFailDelete(response.body().toString());
            }
        }
    }

    /**
     * 设置默认地址
     */
    private void setDefaultAddressImp(int addressId) {
        OkGo.<String>post(NetWorkPath.GET_USER_ADDRESS_IS_DEFAULT+"?id="+addressId)
                .headers(NetWorkPath.HEADER_KEY_AUTH,MyUtil.getAuthToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseDefaultAddress(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtil.i(response.getException().toString());
                        if (isViewAttached()) {
                            getView().onErrorDefault(response.getException().toString());
                        }
                    }
                });

    }

    /**
     * 解析设置默认地址返回的数据
     */
    private void parseDefaultAddress(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessDefault();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailDefault(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorDefault("数据解析有误");
                }
            }

        } else {
            if (isViewAttached()) {
                getView().onFailDefault(response.body().toString());
            }
        }
    }

}
